package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.user.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper,ApUser> implements ApUserService {
    /**
     * 登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {

        //1.正常登录
        if(!StringUtils.isBlank(loginDto.getPhone())&&!StringUtils.isBlank(loginDto.getPassword())){
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            log.info(apUser.getSalt());
            if(apUser==null){
                ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            //2.对比密码
            String salt = apUser.getSalt();
            String pswd = loginDto.getPassword();
            pswd = DigestUtils.md5Hex(pswd + salt);
            if(!pswd.equals(apUser.getPassword())){
                ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //3.返回数据（要User信息和token）但是user信息不能包含password 和 salt
            apUser.setPassword("");
            apUser.setSalt("");
            HashMap<String, Object> map = new HashMap<>();
            map.put("user",apUser);
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            return ResponseResult.okResult(map);
        }else {
            //非正常登录（游客）同样返回token  id = 0
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }

    }
}
